/**
 * 
 */
package teshop.view.catalog;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import teshop.domain.Category;
import teshop.service.CatalogService;
import teshop.util.ForwardToken;

@Component("createCategory")
@Scope("conversation.access")
public class CreateCategory implements Serializable {

	private static final long serialVersionUID = -3105589202122474516L;
	
	private CatalogService catalogService;
	
	private Category category = new Category();
	
	/**
	 * Default empty Constructor for class: CreateCategory
	 */
	public CreateCategory() {
	}
	
	@Autowired
	public CreateCategory(CatalogService pCatalogService) {
		this.catalogService = pCatalogService;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category pCategory) {
		category = pCategory;
	}
	
	@PostConstruct
	public void onLoad() {
		String parentCategoryId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("categoryId");
		if (parentCategoryId != null && parentCategoryId != "")
			category.setParentCategory(catalogService.getCategory(Long.valueOf(parentCategoryId)));
	}
	
	public String save() {
		catalogService.saveCategory(category);
		
		FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "Category is created successfully", "OK");
		FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		
		return ForwardToken.LIST_CATEGORIES;
	}

}
